package org.sfnelson.sk.client.rpc;

import java.io.Serializable;
import java.util.Date;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.sfnelson.sk.client.data.Loot;
import org.sfnelson.sk.client.data.User;
import org.sfnelson.sk.client.event.Created;
import org.sfnelson.sk.client.event.Joined;
import org.sfnelson.sk.client.event.Left;
import org.sfnelson.sk.client.event.ReceivedLoot;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Event implements Serializable {

	private static final long serialVersionUID = -4206638388087071242L;

	public enum Type {
		CREATED,
		JOINED,
		LEFT,
		LOOT
	}

	@PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    Long id;
	@Persistent
	public Date date;
	@Persistent
	public Type type;
	@Persistent
	Long userId;
	@NotPersistent
	User user;
	@Persistent
	Loot loot;
	@Persistent
	String info;
	
	public static Event created(String name) {
		return new Event(Type.CREATED, null, null, name);
	}
	
	public static Event created(User user) {
		return new Event(Type.CREATED, user, null, null);
	}
	
	public static Event joined(User user) {
		return new Event(Type.JOINED, user, null, null);
	}
	
	public static Event left(User user) {
		return new Event(Type.LEFT, user, null, null);
	}
	
	public static Event receivedLoot(User user, Loot loot, String reason) {
		return new Event(Type.LOOT, user, loot, reason);
	}

	private Event(Type type, User user, Loot loot, String info) {
		this.type = type;
		this.userId = user.getId();
		this.user = user;
		this.loot = loot;
		this.info = info;
		
		this.date = new Date();
	}
	
	private Event() {}
	
	public org.sfnelson.sk.client.event.Event asEvent() {
		switch (type) {
		case CREATED:
			return new Created(id, date, user);
		case JOINED:
			return new Joined(id, date, user);
		case LEFT:
			return new Left(id, date, user);
		case LOOT:
			return new ReceivedLoot(id, date, user, loot, info);
		}
		return null;
	}
	
	public Long getUserId() {
		return userId;
	}
	
	public void setUser(User user) {
		this.user = user;
		this.userId = user.getId();
	}
}
